/*
 * @(#)Dispatcher.java
 *
 */

package diablo3.socket;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import diablo3.KeepAMFConnect;
import diablo3.support.ClassPathScanHandler;
import diablo3.support.ReflectOperation;
import diablo3.support.Util;

/**
 * description
 * @author  huangyixiang
 * @version 2012-12-14
 */
public class Dispatcher {
	
	private static final Log LOG = LogFactory.getLog(Dispatcher.class);
	
	public static final String packageName = "diablo3.socket.controller";
	
	private static final Map<String,Class<?>> controllerMap = new HashMap<String, Class<?>>();
	
	static{
        ClassPathScanHandler handler = new ClassPathScanHandler(true, true, null);
        Set<Class<?>> classList = handler.getPackageAllClasses(packageName, true);
        for(Class<?> c : classList){
        	controllerMap.put(c.getName().toLowerCase(), c);
        }
	}

	public void dispatch(String uri) throws Exception{
		uri = uri.replaceAll("\\\\", "/");
		String controllerName = packageName;
		String methodName = null;
		String s[] = uri.split("/");
		
		//转发到其他机器
		if(!Util.isBlank(s[0])
				&& s[0].matches("\\d{1,3}")){
			String ip = "192.168.1." + s[0];
			
			String url = "http://" + ip + uri.substring(s[0].length() + 1);
			HttpClient client = new HttpClient();
			GetMethod method = new GetMethod(url);
			try {
				client.executeMethod(method);
			} catch (Exception e) {
				LOG.error(e.getMessage(),e);
			}
		}
		
		for(int i = 0 ; i < s.length ; i++){
			if(i == s.length - 1){
				methodName = s[i];
			}
			else if(!Util.isBlank(s[i])){
				controllerName += "." + s[i];
			}
		}
		controllerName += "Controller";
		Object controller = ReflectOperation.getInstance(controllerMap.get(controllerName.toLowerCase()));
		ReflectOperation.invokeMethod(controller, methodName, new Object[]{});
	}
	
	public static void main(String[] args) {
				System.out.println("12d".matches("\\d{1,3}"));
	}
}
